/**
 * åºååè¡¨åç±»
 * @auth khl
 * @datetime 2018/7/13
 */
var formUtil = {
	// è·ååéæé®çå¼ï¼å¦ææ²¡æéçè¯è¿ånull
	// elementsä¸ºradioç±»çéåçå¼ç¨
	getRadioValue : function(elements) {
		var value = 0; // nullè¡¨ç¤ºæ²¡æéä¸­é¡¹
		// éIEæµè§å¨
		if (elements.value != undefined && elements.value != '') {
			value = elements.value;
		} else {
			// IEæµè§å¨
			for (var i = 0, len = elements.length; i < len; i++) {
				if (elements[i].checked) {
					value = elements[i].value;
					break;
				}
			}
		}
		return value;
	},

	// è·åå¤éæé®çå¼ï¼å¦ææ²¡æéçè¯è¿ånull
	// elementsä¸ºcheckboxç±»åçinputéåçå¼ç¨
	getCheckboxValue : function(elements) {
		var arr = new Array();
		if(elements instanceof Array){
			for (var i = 0, len = elements.length; i < len; i++) {
				if (elements[i].checked) {
					arr.push(elements[i].value);
				}
			}
			if (arr.length > 0) {
				return arr.join(',');
			} else {
				return 0; // nullè¡¨ç¤ºæ²¡æéä¸­é¡¹
			}
		}else{
			if (elements.checked) {
				return 1;
			}else{
				return 0;
			}
		}
	},

	// è·åä¸ææ¡çå¼
	// elementä¸ºselectåç´ çå¼ç¨
	getSelectValue : function(element) {
		if (element.selectedIndex == -1) {
			return 0; // æ²¡æéä¸­çé¡¹æ¶è¿ånull
		}
		;
		if (element.multiple) {
			// å¤é¡¹éæ©
			var arr = new Array(), options = element.options;
			for (var i = 0, len = options.length; i < len; i++) {
				if (options[i].selected) {
					arr.push(options[i].value);
				}
			}
			return arr.join(",");
		} else {
			// åé¡¹éæ©
			return element.options[element.selectedIndex].value;
		}
	},

	// åºåå
	// formä¸ºformåç´ çå¼ç¨
	serialize : function(form) {
		var arr = new Array(), elements = form.elements, checkboxName = null;
		for (var i = 0, len = elements.length; i < len; i++) {
			field = elements[i];
			// ä¸åéç¦ç¨çè¡¨åå­æ®µ
			if (field.disabled) {
				continue;
			}
			switch (field.type) {
			// éæ©æ¡çå¤ç
			case "select-one":
			case "select-multiple":
				arr.push(encodeURIComponent(field.name) + "="
						+ encodeURIComponent(this.getSelectValue(field)));
				break;

			// ä¸åéä¸åç±»åçè¡¨åå­æ®µ 
			case undefined:
			case "button":
			case "submit":
			case "reset":
			case "file":
				break;

			// åéãå¤éåå¶ä»ç±»åçè¡¨åå¤ç  
			case "checkbox":
				if (checkboxName == null) {
					checkboxName = field.name;
					arr.push(encodeURIComponent(checkboxName)+ "="+ encodeURIComponent(this.getCheckboxValue(form.elements[checkboxName])));
				}
				break;
			case "radio":
				if (!field.checked) {
					break;
				}
			default:
				if (field.name.length > 0) {
					arr.push(encodeURIComponent(field.name) + "="+ encodeURIComponent(field.value));
				}
			}
		}
		return arr.join("&");
	}
};
